package network.server;

import network.message.IMessageReceiver;
import network.message.IMessageSender;
import network.message.SocketMessageReceiver;
import network.message.SocketMessageSender;

import java.io.*;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.Socket;

public class SocketServerProvider implements IServerProvider{
    public String sendMessage(String message) throws IOException {
        /** Define a host server */
        String host = "localhost";
        /** Define a port */
        int port = 11223;

        String response;
        try {
            // Obtain an address object of the server
            InetAddress address = InetAddress.getByName(host);
            // Establish a socket connection
            Socket connection = new Socket(address, port);

            IMessageSender messageSender = new SocketMessageSender(connection);
            messageSender.sendMessage(message);
            IMessageReceiver messageReceiver = new SocketMessageReceiver(connection);
            response = messageReceiver.receiveMessage();

        } catch (ConnectException f) {
            throw (f);
        } catch (IOException f) {
            throw (f);
        }
        return response;
    }
}